package com.klun.designMode.proxy.myProxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 自定义类加载器
 */
public class ZdyClassLoader extends ClassLoader {
    private File baseDir;

    public ZdyClassLoader() {
        String basePath = ZdyClassLoader.class.getResource("").getPath();
        this.baseDir = new File(basePath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = ZdyClassLoader.class.getPackage().getName() + "." + name;
        if (baseDir != null) {
            File classFile=new File(baseDir,name.replaceAll("\\.","/")+".class");
            if (classFile.exists()){
                FileInputStream inputStream=null;
                ByteArrayOutputStream outputStream=null;
                try {
                    inputStream=new FileInputStream(classFile);
                    outputStream=new ByteArrayOutputStream();
                    byte[]  buff=new byte[1024];
                    int len;
                    while ((len=inputStream.read(buff))!=-1){
                        outputStream.write(buff,0,len);
                    }
                    return  defineClass(className,outputStream.toByteArray(),0,outputStream.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    classFile.delete();
                    if (inputStream!=null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null==outputStream){
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}